import { GLOBAL_CONFIG } from '@/config/constant'
import { IGlobalPinia } from '@/types/global'
import { darkTheme, lightTheme, useOsTheme } from 'naive-ui'
import { defineStore } from 'pinia'

const sessionConfig = sessionStorage.getItem(GLOBAL_CONFIG)
const sessionConfigObj = sessionConfig ? JSON.parse(sessionConfig) : null

const defaultConfig: IGlobalPinia = {
    // 错误页
    exception: {
        title: '404 资源不存在',
        description: '生活总归带点荒谬',
        size: 'large',
        status: '404'
    },

    // 头部高度
    headerHeight: 64,

    // 间距
    gap: 24,

    // 主题
    theme: 'os'
}

const osThemeRef = useOsTheme()

export const useGlobalStore = defineStore('global', {
    state: (): IGlobalPinia => sessionConfigObj || defaultConfig,
    getters: {
        themed(state) {
            if (state.theme === 'dark') {
                return darkTheme
            } else if (state.theme === 'light') {
                return lightTheme
            } else {
                return osThemeRef.value === 'dark' ? darkTheme : lightTheme
            }
        }
    },
    actions: {
        setState(config: Partial<IGlobalPinia> = {}) {
            this.$patch(config)

            sessionStorage.setItem(GLOBAL_CONFIG, JSON.stringify(this.$state))
        },
        setCssVars() {
            const style = document.createElement('style')
            style.innerHTML = `
                :root {
                    --gap: ${this.gap}px;
                    --header-height: ${this.headerHeight}px;
                }
            `
            document.head.appendChild(style)
        }
    }
})
